export const codeMirror1 = `
    // useHook.ts
    import { useRequest } from "ahooks";

    export const useHook = (props: {
    commitFn: (params: any) => Promise<any>; // 提交函数
    pollingFn: (requestId: string) => Promise<any>; // 轮询函数
    setLoading: (loading: boolean) => void;
    successCallback: (data: any) => void; // 成功回调
    }) => {
    const { commitFn, pollingFn, successCallback } = props;

    // 轮询任务
    const getPollingData = async (
        requestId: string,
        success: (data: any) => void
    ) => {
        const data = await pollingFn(requestId);
        // 这里最好是统一返回值结构，如果不统一，这里还需要修改
        if (data === null) {
        // 如果任务未完成，继续轮询
        // todo: 优化轮询逻辑
        } else {
        // 如果任务完成，停止轮询
        success(data);
        cancel();
        }
    };

    const { run: getPollingDataRun, cancel } = useRequest(getPollingData, {
        pollingInterval: 2000, // 2s 轮询一次
        pollingWhenHidden: false, // 页面隐藏时停止轮询
        manual: true,
    });

    // 使用 useRequest 调用请求函数
    const { run: commitRun } = useRequest(commitFn, {
        manual: true, // 手动触发请求
        onSuccess: (result: string) => {
        getPollingDataRun(result, successCallback);
        },
    });
    return { commitRun, getPollingDataRun };
    };
`;

export const codeMirror2 = `
// pollAfterCommit.tsx
    // 调用方式 
    import { addUser, getTaskStatus } from "@/services";
    import { useHook } from "./useHook";
    import { generateRandomChineseName } from "@/utils/utils";

    export const PollAfterCommit: React.FC = () => {
        const [loading, setLoading] = useState<boolean>(false);
        const { commitRun } = useHook({
            commitFn: addUser,
            pollingFn: getTaskStatus,
            setLoading,
            successCallback: (data) => {
            console.log("data:", data);
            setLoading(false);
            },
        });

        // 处理缓存按钮
        const handleClick = () => {
            setLoading(true);
            commitRun({ name: generateRandomChineseName(), age: 18 });
        };

        return (
            <div className="w-[80vw]">
                <Button type="primary" loading={loading} onClick={handleClick}>
                    点击调用
                </Button>
            </div>
        );
    };
`;

export const codeMirror3 = `
    // service.ts
    // 新增用户
    export const addUser = (params: { name: string; age: number }) => {
      return request.post<any>("http://localhost:3002/users", params);
    };
    
    // 获取任务状态
    export const getTaskStatus = (requestId: string) => {
      return request.get<any>("http://localhost:3002/users/status/requestId");
    };
`;
